package com.zk.cq.util;

import com.alibaba.fastjson.JSONObject;
import com.zk.cq.annotation.Filter;
import com.zk.cq.constant.FilterRuleEnum;
import com.zk.cq.model.bo.BeanMethodBO;
import org.springframework.util.StringUtils;

public class FilterKeywordUtil {

    public static Boolean filter(BeanMethodBO beanMethodBO, JSONObject param) {
        Filter annotation = beanMethodBO.getMethod().getAnnotation(Filter.class);
        if (annotation == null){
            return true;
        }
        String keyword = annotation.keyword();
        String message = param.getString("message");
        FilterRuleEnum rule = annotation.rule();
        if (StringUtils.isEmpty(keyword)) {
            return true;
        }
        return handler(keyword, rule, message);
    }

    private static Boolean handler(String keyword, FilterRuleEnum rule, String message) {
        if (FilterRuleEnum.EQUAL.equals(rule) && keyword.equals(message)){
                return true;
        }else if(FilterRuleEnum.CONTAIN.equals(rule) && message.contains(keyword)){
                return true;
        }else if(FilterRuleEnum.REGULAR.equals(rule) && message.matches(keyword)){
            return true;
        }
        return false;
    }
}
